package com.tianqingwl.gsystem.security.filter;

import com.google.code.kaptcha.Constants;
import com.tianqingwl.gsystem.security.exception.ValidateCodeException;
import com.tianqingwl.gsystem.security.handler.LoginFailJsonHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class CaptchaValidateFilter extends OncePerRequestFilter {
    private LoginFailJsonHandler loginFailJsonHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        //仅拦截登录请求
        if (httpServletRequest.getRequestURI().contains("/login")&&!httpServletRequest.getRequestURI().contains("/login.html")){
            try{
                String captcha = httpServletRequest.getParameter("captcha");

                if (StringUtils.isEmpty(captcha)){
                    throw new ValidateCodeException("验证码不能为空！");
                }
                HttpSession session = httpServletRequest.getSession();
                String sessionCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
                if (!sessionCaptcha.equalsIgnoreCase(captcha)){
                    throw new ValidateCodeException("验证码输入有误！");
                }

            }catch (AuthenticationException e){
                loginFailJsonHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return ;
            }

        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    public void setLoginFailJsonHandler(LoginFailJsonHandler loginFailJsonHandler) {
        this.loginFailJsonHandler = loginFailJsonHandler;
    }
}
